#include "Resources.h"
using namespace SolidityEngine;

Resources::Resources()
{}

void Resources::Initialize()
{
    //Get the current working directory
    char* buf=new char[PathMax];
    getcwd(buf,PathMax);
    #ifdef _WIN32
        Root=std::string(buf)+"\\Assets\\";
    #else
        Root=std::string(buf)+"/Assets/";
    #endif


    //Does this directory exist?
    DIR* assetdir=opendir(Root.c_str());
    if (assetdir==NULL){
    //create the directory
    #ifdef _WIN32
        mkdir(Root.c_str());
    #else
        mkdir(Root.c_str(),0777);
    #endif
    }

    Scan();
}

Resources::~Resources()
{
    //dtor
}


void Resources::PutBackResource(const std::string& name){
    Resource* res=GetResource<Resource>(name);
    if(res) res->Unload();
};

void Resources::PutBackResource(int ID){
    Resource* res=GetResource<Resource>(ID);
    if(res) res->Unload();
};

void ReadDir(const std::string& path, std::list<std::string>* files){
    //Open the current directory
    DIR* dirp=opendir(path.c_str());
    if(dirp==NULL){
        throw "Error Reading Directory";
        return;
    }
    bool end=false;
    while(!end){
        //read the next entry
        dirent* entry=readdir(dirp);
        if(!entry){
            end=true;
            break;
        }
        else if(entry){
            if(entry->d_name[0]!='.'){ //ignore if the first character is a dot

                std::string entrypath=path+std::string(entry->d_name);

                //check the status of the element
                struct stat buffer;

                int status;
                status=stat(entrypath.c_str(),&buffer);
                //if the entry is not a directory.. add to the file list
                if(status==-1) break;
                if S_ISREG(buffer.st_mode){
                    //This is a file.. add to the list
                    files->push_back(std::string(entrypath));
                }
                if S_ISDIR(buffer.st_mode){
                    //This is a directory
                    #ifdef _WIN32
                    ReadDir(std::string(entrypath)+"\\",files);
                    #else
                    ReadDir(std::string(entrypath)+"/",files);
                    #endif

                }
            }
        }
    }

}

//Scan the Asset directories for resources
void Resources::Scan()
{
    std::list<std::string> filelist;

    //Read in all asset paths
    ReadDir(Root,&filelist);

    std::list<std::string>::iterator iter=filelist.begin();

    std::cout<<"Scanning resource folders.."<<std::endl;
    while(iter!=filelist.end()){
        try{
            std::string suffix=iter->substr(iter->rfind("."));
            #ifdef _WIN32
            std::string name=iter->substr(iter->rfind("\\")+1, iter->rfind(".")-iter->rfind("\\")-1);
            #else
            std::string name=iter->substr(iter->rfind("/")+1, iter->rfind(".")-iter->rfind("/")-1);
            #endif

            if(suffix==".png")
            {
                ResourcePool.insert(Resource_ptr(new ImageResource((*iter),name)));
            }
            if(suffix==".ttf")
            {
                ResourcePool.insert(Resource_ptr(new FontResource((*iter),name)));
            }
            if(suffix==".wav")
            {
                ResourcePool.insert(Resource_ptr(new AudioClipResource((*iter),name)));
            }
            std::cout<<"Found:"<<name<<std::endl;

        }
        catch(...){
            std::cout<<"Warning: Unknown file format: "<<*iter<<std::endl;
        }
        iter ++;
    }
}

int Resources::PathMax=100;
std::string Resources::Root="";
std::set<Resource_ptr> Resources::ResourcePool = std::set<Resource_ptr>();

